package com.tensquare.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2021/6/25.
 */
@Component
public class ManagementFilter extends ZuulFilter {

    //过滤器类型,pre:可以在请求被路由之前调用,route ：在路由请求时候被调用,
    // post ：在route和error过滤器之后被调用,error ：处理请求时发生错误时被调用
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器顺序  优先级为0，数字越大，优先级越低
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否开启过滤器   是否执行该过滤器，此处为true，说明需要过滤
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 在过滤器中将请求头信息转发到各个微服务中
     * 1.如果合法,请求转发到微服务
     * 2.如果非法token返回权限不足
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("后台zuul过滤器生效了*******");
        //获取上下文对象RequestContext
        RequestContext context = RequestContext.getCurrentContext();
        //获取request,response对象
        HttpServletRequest request = context.getRequest();
        String header = request.getHeader("Authorization");

        //将请求头发转到各个微服务
        if (StringUtils.isNotBlank(header) && header.startsWith("Bearer ")){
            String token = header.substring(7);
            //解析token
            Claims claims = jwtUtil.parseToken(token);
            if(claims != null){
              String role = (String) claims.get("role");
              if ("admin".equals(role)){
                  //该token合法
                  context.addZuulRequestHeader("Authorization",header);
                  return null;
              }
            }
        }
        //非法操作
        context.setResponseStatusCode(401);//返回http状态码
        Result result = new Result(false, StatusCode.ACCESSS_ERROR, "对不起,你没权限操作");
        String res = JSONObject.toJSONString(result);
        //指定返回数据位json
        context.getResponse().setContentType("text/json;charset=utf-8");
        context.setResponseBody(res);  //响应数据
        context.setSendZuulResponse(false); //停止转发
        return null;
    }
}
